#if defined(MIX_RTK)

#include "samples.h"

SHELL_CMD_FN(_rtk_sample_mutex);

SHELL_REGISTER_CMD(
    register_sample_mutex,
    SHELL_SETUP_CMD("sample-mutex", "Kernel API example of: mutex", _rtk_sample_mutex, NULL), //
);

static rtk_thread_t s_thread1_handle;
static rtk_mutex_t s_mutex_handle;

static void _thread_1(void *arg)
{
    sh_t *sh_hdl = arg;
    rtk_thread_t *thread;
    const char *thread_name;

    thread = rtk_thread_get_self();
    thread_name = rtk_thread_get_name(thread);
    printf("this is '%s' running\r\n", thread_name);

    printf("%s: try to lock\r\n", thread_name);
    if (rtk_mutex_lock(&s_mutex_handle, RTK_WAIT_FOREVER) != RTK_OK)
    {
        SYS_LOG_ERR("mutex lock fail!");
        rtk_thread_delete(NULL);
        return;
    }
    printf("%s: lock success. unlock after 500 ms ...\r\n", thread_name);

    rtk_thread_sleep(500);

    printf("%s: time up\r\n", thread_name);

    printf("%s: unlock\r\n", thread_name);
    rtk_mutex_unlock(&s_mutex_handle);

    printf("%s: run complete\r\n", thread_name);
    rtk_thread_delete(NULL);
}

SHELL_CMD_FN(_rtk_sample_mutex)
{
    tag();

    rtk_thread_t *thread;
    const char *thread_name;

    thread = rtk_thread_get_self();
    thread_name = rtk_thread_get_name(thread);

    do
    {
        printf("create a mutex object\r\n");
        if (rtk_mutex_create(&s_mutex_handle, "mutex1") != RTK_OK)
        {
            break;
        }

        printf("create and wait thread-1 to run ...\r\n");
        rtk_thread_create(&s_thread1_handle,
                         "thread-1",
                         _thread_1,
                         sh_hdl,
                         0x400,
                         1,
                         0);
        rtk_thread_sleep(100);

        printf("this is '%s' running\r\n", rtk_thread_get_name(thread));

        printf("%s: try to lock\r\n", thread_name);
        if (rtk_mutex_lock(&s_mutex_handle, RTK_WAIT_FOREVER) != RTK_OK)
        {
            SYS_LOG_ERR("mutex lock fail!");
            break;
        }
        printf("%s: lock success\r\n", thread_name);

        printf("%s: unlock\r\n", thread_name);
        rtk_mutex_unlock(&s_mutex_handle);

        printf("%s: waiting 'thread-1' complete ...\r\n", thread_name);
        rtk_thread_sleep(100);

        printf("objects can be deleted when they are no longer used\r\n");
        rtk_mutex_delete(&s_mutex_handle);

        return 0;

    } while (0);

    rtk_mutex_delete(&s_mutex_handle);

    printf("operate fail!\r\n");
    return -1;
}

#endif /* #if defined(MIX_RTK) */
